package com.cpms.framework.log.filter;

import com.cpms.framework.common.constants.CoreCommonConstant;
import com.cpms.framework.common.utils.CsRandomUtil;
import com.cpms.framework.log.wrapper.RequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gulang
 * @Description:
 * @time: 2022/1/29 18:06
 */
public class OnceFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        ServletRequest requestWrapper = null;
        setRequestChainInfo(request);
        if(request instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper( request);
        }
        // 让下一个filter生效
        if(requestWrapper == null) {
            filterChain.doFilter(request, response);
        } else {
            filterChain.doFilter(requestWrapper, response);
        }
        // 清除MDC
        MDC.clear();
    }


    /**
     * 设置整个请求链路信息
     * @param req HttpServletRequest
     */
    private void setRequestChainInfo(HttpServletRequest req) {
        String traceId = req.getHeader(CoreCommonConstant.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = CsRandomUtil.randomUUID(true,true);
        }
        req.setAttribute(CoreCommonConstant.TRACE_ID,traceId);
        MDC.put(CoreCommonConstant.TRACE_ID, traceId);
        // 设置用户信息
        MDC.put(CoreCommonConstant.USER_INFO,req.getHeader(CoreCommonConstant.USER_INFO));
    }


}
